package com.gdut.simple.model.impl;

import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.data.entity.Post;
import com.gdut.simple.data.entity.User;
import com.gdut.simple.model.IPublishModel;

import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;

public class PublishModelImpl implements IPublishModel {

    @Override
    public void publish(final User user, final String[] imagePaths, final String content, final RequestCallback<String> callback) {
        if (imagePaths == null || imagePaths.length == 0) {
            Post post = new Post();
            post.setAuthor(user);
            post.setContent(content);
            post.setImages(null);
            post.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        if (callback != null) {
                            callback.onSuccess(s);
                        }
                    } else {
                        if (callback != null) {
                            callback.onFailure(e.getMessage());
                        }
                    }
                }
            });
            return;
        }
        BmobFile.uploadBatch(imagePaths, new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> files, List<String> urls) {
                if (files.size() == imagePaths.length) {
                    Post post = new Post();
                    post.setAuthor(user);
                    post.setContent(content);
                    post.setImages(files);
                    post.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                if (callback != null) {
                                    callback.onSuccess(s);
                                }
                            } else {
                                if (callback != null) {
                                    callback.onFailure(e.getMessage());
                                }
                            }
                        }
                    });
                }
            }

            @Override
            public void onProgress(int i, int i1, int i2, int i3) {

            }

            @Override
            public void onError(int i, String s) {
                if (callback != null) {
                    callback.onFailure(s);
                }
            }
        });
    }
}
